using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using ShoppingCenter.Backend.Api.Model;
using ShoppingCenter.Backend.Api.Params;
using ShoppingCenter.Backend.Api.Repository;
using ShoppingCenter.Backend.Api.Utils;

namespace ShoppingCenter.Backend.Api.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class AdminsController : ControllerBase
    {
        private IConfiguration _configuration;
        //初始化token
        private TokenParameter _toKenParameter;

        private IRepository<Admin> _adminRepository;
        private IRepository<User> _usersRepository;

        public AdminsController(IConfiguration configuration, IRepository<User> usersRepository, IRepository<Admin> adminRepository)
        {
            _configuration = configuration;
            _usersRepository = usersRepository;
            _adminRepository = adminRepository;
            _toKenParameter = _configuration
                   .GetSection("TokenParameter")
                   .Get<TokenParameter>();
        }


        //登录获取token
        [AllowAnonymous]
        [HttpPost, Route("token")]
        public dynamic GetToken(CURUser newAdmin)
        {
            var username = newAdmin.Name.Trim();
            var password = newAdmin.Password.Trim();

            var admin = _adminRepository.Table
                    .Where(x => x.Name == username && x.Password == password)
                    .FirstOrDefault();


            if (admin == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不正确，请确认后重试"
                };
            }

            var token = ToKenHelper.GenerateToekn(_toKenParameter, admin.Name);
            var refreshToken = "112358";

            return new
            {
                Code = 1000,
                Data = new { Token = token, refreshToken = refreshToken, admin },
                Msg = "管理员登录成功^_^"
            };
        }


        //获取所有管理员
        public dynamic Get()
        {

            var currentPage = int.Parse(Request.Query["currentPage"][0]);
            var pageSize = int.Parse(Request.Query["pageSize"][0]);

            var admins = _adminRepository.Table.ToList();

            // 分页
            var admin = admins.Skip((currentPage - 1) * pageSize).Take(pageSize);

            return new
            {
                Code = 1000,
                Data = new
                {
                    Data = admin,
                    Pager = new { currentPage, pageSize, totalSize = admins.Count() }
                },
                Msg = "获取所有管理员成功"
            };
        }

        //模糊查询管理员
        [HttpPost, Route("queryAdmin")]
        public dynamic GetQuery(QueryData queryAdminname)
        {

            var querydata = queryAdminname.data.Trim();

            var admin = _adminRepository.Table.Where(x => x.Name.Contains(querydata));

            return new
            {
                Code = 1000,
                Data = admin,
                Msg = "查询成功"
            };

        }

        //添加
        [HttpPost]
        public dynamic Post(CURUser newAdmin)
        {
            var username = newAdmin.Name.Trim();
            var password = newAdmin.Password.Trim();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {

                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "账号或密码不能为空"
                };
            }

            var u = _usersRepository.Table.Where(x => x.Name == username).ToList().FirstOrDefault();
            var admin = _adminRepository.Table.Where(x => x.Name == username).ToList().FirstOrDefault();

            //判断当前用户名是否已经注册
            if (u != null || admin != null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "当前用户名已存在,请换个用户名后重试"
                };
            }


            var adminAdd = new Admin
            {
                Name = username,
                Password = password,
                Remarks = newAdmin.Remarks,
            };

            //将账号密码插入到Users表中
            _adminRepository.Insert(adminAdd);


            return new
            {
                Code = 1000,
                Data = adminAdd,
                Msg = "创建用户成功"
            };

            //将结果实例化后输出

        }

        //根据id修改用户信息
        [HttpPut("{id}")]
        public dynamic Put(int id, CURUser updateAdmin)
        {
            var username = updateAdmin.Name.Trim();
            var password = updateAdmin.Password.Trim();


            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "账号或密码不能为空"
                };
            }


            //通过Id获取要修改的管理员
            var adminUpdate = _adminRepository.GetById(id);

            if (adminUpdate == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "你要更新的管理员不存在"
                };
            }

            var u = _usersRepository.Table.Where(x => x.Name == username).ToList().FirstOrDefault();
            var admin = _adminRepository.Table.Where(x => x.Name == username).ToList().FirstOrDefault();

            if (u != null || (admin != null && admin.Id != id))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "当前用户名已存在,请换个用户名后重试"
                };
            }

            //将要修改的账号密码重新赋给Admin
            adminUpdate.Name = username;
            adminUpdate.Password = password;
            adminUpdate.Remarks = updateAdmin.Remarks;

            //更新数据
            _adminRepository.Update(adminUpdate);

            return new
            {
                Code = 1000,
                Data = adminUpdate,
                Msg = "更新数据成功"
            };

            // return JsonHelper.Serialize(res);

        }

        //根据id删除用户
        [HttpDelete("{id}")]
        public dynamic Dalete(int id)
        {

            var user = _adminRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = string.Format("无法删除id为{0}的管理员", id)
                };
            }

            _adminRepository.Delete(id);

            return new
            {
                Code = 1000,
                Data = "",
                Msg = "删除管理员成功"
            };
        }
    }
}